package com.example.demo.materialPurchase.controller;


import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.common.ResponseData;
import com.example.demo.materialPurchase.entity.PlanDeadline;
import com.example.demo.materialPurchase.service.impl.PlanDeadlineServiceImpl;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wangxuan
 * @since 2021-05-08
 */
@RestController
@RequestMapping("/materialPurchase/plan-deadline")
@PreAuthorize("hasAnyAuthority('4','1','2','6')")
@CrossOrigin(origins = {"*"})
public class PlanDeadlineController {

	@Autowired
	private PlanDeadlineServiceImpl planServiceImpl;
	
	/**
	 * 查询 截止日期： 每次查询id最大的一个记录。
	 * @return
	 */
	@GetMapping("/selPlanDate")
	public ResponseData selPlanDeadLine() {
		
		QueryWrapper<PlanDeadline> wrapper = new QueryWrapper<PlanDeadline>();
		wrapper.orderByDesc("id");
		wrapper.last("limit 1");
		PlanDeadline plan = new PlanDeadline();
		plan = planServiceImpl.getOne(wrapper);
		
		return ResponseData.buildOk(plan);
	}
	
	/**
	 * 插入新的截止日期
	 * @return
	 */
	
	@PostMapping("/insPlanDate")
	public ResponseData insPlanDateLine(@RequestParam("deadline") String deadline) {
		
		PlanDeadline plan = new PlanDeadline();
		plan.setDeadline(Integer.valueOf(deadline));
		try {
			planServiceImpl.save(plan);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
			return ResponseData.buildError("服务器操作有误，新建失败！");
		}
		
		return ResponseData.buildOk("新建成功！");
	}
	
	/**
	 * 根据 Id 修改 截止日期
	 * @param id
	 * @return
	 */
	@GetMapping("/updDateById")
	public ResponseData UpdDateById(@RequestParam("id") Integer id, @RequestParam("deadline") Integer deadline) {
		
		PlanDeadline plan = new PlanDeadline();
		plan.setId(id);
		plan.setDeadline(deadline);
		
		try {
			planServiceImpl.updateById(plan);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(e);
			return ResponseData.buildError("更新失败！");
		}
		
		return ResponseData.buildOk("更新成功！");
	}
	
}

